//
// Created by xidian on 2024/12/25.
//

#include "include/DataSave.h"
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

DataSave::DataSave()
{
    isStopped = false;
    sem_init(&sem, 0, 0);
}

void DataSave::startSave()
{
    isStart = true;
    thread = std::make_shared<std::thread>(&DataSave::saveThread, this);
}

DataSave::~DataSave()
{
    isStopped = true;
    sem_post(&sem);

    if(isStart)
    {
        thread->join();
    }

    sem_destroy(&sem);
}

void DataSave::push(uint8_t *data)
{
    if(!isStart){
        return;
    }


    memcpy(buf[writePtr], data, 1200);
    writePtr++;
    writePtr = writePtr % _N;
//    std::cout << "writePtr:  "  <<writePtr << std::endl;
    sem_post(&sem);
}

void DataSave::saveThread()
{
    std::string fileName = getFileName();
    FILE *fp = fopen(fileName.c_str(), "wb+");

    while (true)
    {
        sem_wait(&sem);

        if (isStopped)
        {
            break;
        }
//        std::cout << "readPtr:  "  <<readPtr << std::endl;
        fwrite(buf[readPtr], sizeof(uint8_t), 1200, fp);
        readPtr++;
        readPtr = readPtr % _N;
    }

    fclose(fp);
}

std::string DataSave::getFileName()
{
    std::time_t t = std::time(nullptr);
    std::tm *now = std::localtime(&t);

    std::ostringstream oss;
    oss << std::put_time(now, "../data/udpRecvData/%Y%m%d_%H%M%S");
    std::string fileName = oss.str() + ".dat";

    return fileName;
}